package com.da.javatest.interview.other.print;

import java.util.concurrent.Semaphore;

/**
 * @author chenlida
 * @date 2020/10/20 14:52
 * @description
 */
public class PrintABC3 {
    private int times;
    private Semaphore s1 = new Semaphore(1);
    private Semaphore s2 = new Semaphore(0);
    private Semaphore s3 = new Semaphore(0);

    public PrintABC3(int times) {
        this.times = times;
    }

    private void print(String msg, Semaphore current, Semaphore next) {
        for (int i = 0; i < times; i++) {
            try {
                current.acquire();
                System.out.print(msg);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                next.release();
            }

        }
    }

    public void printA() {
        print("A", s1, s2);
    }

    public void printB() {
        print("B", s2, s3);
    }

    public void printC() {
        print("C", s3, s1);
    }

    public static void main(String[] args) {
        PrintABC3 printABC1 = new PrintABC3(10);
        new Thread(printABC1::printA).start();
        new Thread(printABC1::printB).start();
        new Thread(printABC1::printC).start();
    }
}
